<?php

namespace App\Http\Services;

use App\Exceptions\ApiException;
use App\Models\Request\QueryPageResult;
use App\Models\Request\ReqParam;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;

class BaseService
{
    public function page(string $tableName, ReqParam $params, bool $isAll)
    {
        $data = $params->data;
        $res = DB::table($tableName);

        if (Arr::exists($data, 'filter')) {
            foreach ($data['filter'] as $item) {
                $res->where($item['field'], $item['criteria'], $item['target']);
            }
        }

        if (Arr::exists($data, 'sort')) {
            foreach ($data['sort'] as $item) {
                $res->orderBy($item['field'], $item['type']);
            }
        }

        if ($isAll) {
            $res = $res->get();
            return new QueryPageResult(null, null, null, $res);
        }

        $res = $res->paginate($data['limit'], ['*'], 'page', $data['rows']);
        $res = json_decode(json_encode($res), true);
        return new QueryPageResult($res['current_page'], $res['per_page'], $res['total'], $res['data']);
    }
}
